 /* eslint-disable */
import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'

// 创建axios实例
const service = axios.create({
  baseURL: '/', // api的base_url
  timeout: 15000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(config => {
  if(window.userType&&(config.url.indexOf('/banadmin/solution_workbench/')!==-1 || config.url.indexOf('/admin/solution_im/')!==-1)){   //学习中心四期调用答疑相关接口时，优先启动Authorization判断用户信息；
    config.headers['Authorization'] = 'Basic '+window.sname
  }
  if (config.method == 'get') {
    config.url += ('?t=' + new Date().getTime())
  }

  if(store.getters.action == config.method
      && (store.getters.uri == config.url || store.getters.uri == '/'+config.url) ) {  //请求需要验证
    config.headers['ZL-VCode'] = store.getters.vCode
    
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
   * errcode为非0是抛错
   */
    const res = response.data
    if (res.errcode !== 0) {
      Message({
        showClose: true,
        message: res.errmsg,
        type: 'error',
        duration: 3 * 1000
      })

      // 1001:没有操作权限，登录状态失效
      if (res.errcode === 1001) {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
      }
      return Promise.reject(res)
    } else {
      return response.data
    }
  },
  error => {
    var res = {
      errcode: -2000,
      errmsg: '网络错误！'
    }
    Message({
      showClose: true,
      message: res.errmsg,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(res)
  }
)

export default service
